<?php
class AdminController extends Core_Controller_Action {
	protected $_mapper;
	protected $_name;
	protected $_id;
	protected $_menuEntry = 'admin';
	protected $_style = array ('/styles/admin.css', '/styles/jquery-ui-datepicker.css', '/styles/cleditor/jquery.cleditor.css' );
	protected $_script = array ('/scripts/admin.js', '/scripts/jquery-ui-datepicker.js', '/scripts/jquery.cleditor.min.js' );
	protected $_redirector;
	
	public function init() {
		$name = $this->_name = ucwords ( strtolower ( $this->getRequest ()->getParam ( 'name', 'category' ) ) );
		$this->_id = ( int ) $this->getRequest ()->getParam ( 'id', 0 );
		$this->_mapper = Zend_Registry::get ( 'api' )->$name;
		$this->_redirector = $this->_helper->getHelper ( 'Redirector' );
	}
	
	public function indexAction() {
	
	}
	
	public function readAction() {
		$this->view->parent_id = $this->_id;
		$this->view->control = 'admin' . $this->_name;
		$this->view->metadata = $this->_mapper->getMetaData ( $this->_id );
		$this->view->back_url = $this->_mapper->getBackUrl ( $this->_id, 0 );
		$this->view->elements = $this->_mapper->getAll ( $this->_id );
	}
	
	public function createAction() {
		$request = $this->getRequest ();
		$form = $this->_mapper->getForm ( $this->_id );
		
		if (! $request->isPost () || ! $form->isValid ( $request->getPost () ))
			return $this->view->form = $form;
		
		$this->_mapper->create ( $form, $this->_id );
		$this->_redirect ( $this->_mapper->getBackUrl ( $this->_id, 1 ) );
	}
	
	public function updateAction() {
		$request = $this->getRequest ();
		$row = $this->_mapper->getOne ( $this->_id );
		$form = $this->_mapper->getForm ( isset ( $row->parent_id ) ? $row->parent_id : null, false );
		$data = $row->toArray ();
		if (isset ( $data ['password'] ))
			unset ( $data ['password'] );
		$form->populate ( $data );
		
		if (! $request->isPost () || ! $form->isValid ( $request->getPost () ))
			return $this->view->form = $form;
		
		$this->_mapper->edit ( $form, $this->_id );
		
		$this->_redirect ( $this->_mapper->getBackUrl ( $this->_id, 2 ) );
	}
	
	public function deleteAction() {
		$this->_helper->viewRenderer->setNoRender ( true );
		$id = $this->_mapper->find ( $this->_id )->parent_id;
		$this->_mapper->remove ( $this->_id );
		
		$this->_redirect ( $this->_mapper->getBackUrl ( $id, 3 ) );
	}
	
	public function syncAction() {
		$nav = Zend_Registry::get ( 'Zend_Navigation' );
		$catalog = $nav->findOneBy ( 'id', 'admin' );
		$catalog->setActive ( true );
		$catalog->findOneBy ( 'id', 'sync' )->setActive ( true );
	}
}